package com.caijg.exception;

import com.caijg.domain.vo.Result;
import com.caijg.utils.WebUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
    // 业务异常（HTTP 200 + 业务错误码）
    @ExceptionHandler(CustomException.class)
    public Result handleBusinessException(CustomException e) {
        logException(e);
        return Result.error(e.getCode(), e.getMessage());
    }

    // 404 资源不存在（HTTP 404）
    @ExceptionHandler({NoHandlerFoundException.class, NoResourceFoundException.class})
    public Result handle404Exception(Exception e) {
        logException(e);
        return Result.error(ResultCode.NOT_FOUND.getCode(), "请求资源不存在");
    }

    // 系统级异常（HTTP 500）
    @ExceptionHandler(Exception.class)
    public Result handleSystemException(Exception e) {
        logException(e);
        return Result.error(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMsg());
    }

    // 通用日志记录方法
    private void logException(Exception e) {
        HttpServletRequest request = WebUtils.getRequest();
        assert request != null;
        log.error("[异常追踪] URI: {} | Method: {}",
                request.getRequestURI(),
                request.getMethod());
        log.error("[异常详情] Type: {} | Message: {}",
                e.getClass().getSimpleName(),
                e.getMessage(),
                e);
    }
}